/**
 * Created by xurui on 2018/12/21.
 */
(function () {
    'use strict';
    angular
        .module('logcenterApp')
        .controller('simpleSearchController', simpleSearchController)
    simpleSearchController.$inject = ['$scope', '$rootScope', '$state', 'searchService', '$localStorage'];

    function simpleSearchController($scope, $rootScope, $state, searchService, $localStorage) {
        var requestData = "";
        var isLoadMore = true;
        var analysisData = "";
        var array = new Array();
        $scope.selected = [];
        $scope.available = [];
        $scope.columns = [
            // {field: "_source.logtime", title: "Time", width yyyyyyh0px"},
            // {
            //     field: "_source", title: "_source", width: "600px", template: function (dataItem) {
            //         return JSON.stringify(dataItem["_source"]);
            //     }
            // }

        ];
        $scope.isQuickQuery = true;
        $scope.param = {
            priority: "logstash-*",
            startTime: getToday00Clock(),
            endTime: getToday11Clock(),
            key: "*"

        };
        $scope.query = function () {
            requestData = generate();
            $scope.ELKGridOptions.dataSource.read();
        };
        $scope.ELKGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columnMenu: true
        };
        $scope.ELKGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    searchService.simpleQuery(requestData, $scope.param.priority).then(function (resp) {
                        var data = resp.data.hits.hits;
                        // $scope.selected=[];
                        // $scope.available=[];
                        $scope.columns = [
                            {field: "_source.logtime", title: "Time", width: "100px"},
                            {
                                field: "_source", title: "_source", width: "600px", template: function (dataItem) {
                                    return JSON.stringify(dataItem["_source"]);
                                }
                            }



                        ];
                        let arr = $scope.selected.map((item,index)=>{

                            if (item == "@timestamp") {
                            item = 'timestamp';
                        } else if (item == '@version') {
                            item = 'version';
                        }
                        if (item.indexOf("_") != -1 && item.indexOf("_source") == -1 && $scope.columns.in_array(item) == true) {
                            $scope.columns.push({field: item, title: item, width: "200px"});
                        }
                        else if ( $scope.columns.in_array(item) == false) {
                            $scope.columns.push({field: "_source." + item, title: item, width: "100px"});

                        }
                        angular.forEach($scope.columns, function (columnsItem) {
                            if (columnsItem.title == "_source") {
                                $scope.columns.splice(1, 1);
                            }
                        });
                    });
                        console.log($scope.selected);
                        console.log($scope.available);

                      analysisData = resp.data.aggregations.agg_dateHistogram.buckets;
                        data.length == 30 ? isLoadMore = true : isLoadMore = false;
                        angular.forEach(data, function (item) {
                            item._source.sourceId = item._id;
                            item._source.username = item._source.uid;
                            item._source.timestamp = item._source['@timestamp'];
                            item._source.version = item._source['@version'];
                            array.push(item);
                            //console.log(array);
                        });

                        if (array.length >0){
                            if ($scope.selected == 0) {
                                $scope.available = Object.keys(array[0]._source);
                                console.log($scope.available);
                                $scope.listGroup = Object.keys(array[0]._source);
                                //if ($scope.selected.length == 0)
                                console.log($scope.selected);
                                angular.forEach(Object.keys(array[0]._source), function (item) {
                                    if (item == "beat") {
                                        $scope.available.push("beat.hostname");
                                        $scope.available.push("beat.name");
                                        $scope.available.push("beat.version");
                                    }
                                });
                                $scope.queryEcharts = 1;
                            }else {
                                console.log($scope.available);

                            }
                            console.log($scope.columns);



                        }else {
                            $scope.queryEcharts = 0;
                            $scope.available=[];
                            $scope.selected=[];
                        }
                        xyAxisData(analysisData);

                        e.success(array);

                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (requestData == "") {
                    e.preventDefault();
                }
            },
            schema: {
                model: $scope.ELKModel
            }
        });
        $scope.addSelected = function (index, item) {
            console.log(index)
            console.log(item)
            $scope.selected.push(item);
            if (index > -1) {
                $scope.available.splice(index, 1);
            }
            if (item == "@timestamp") {
                item = 'timestamp';
            } else if (item == '@version') {
                item = 'version';
            }
            if (item.indexOf("_") != -1 && item.indexOf("_source") == -1) {
                $scope.columns.push({field: item, title: item, width: "200px"});
            } else {
                $scope.columns.push({field: "_source." + item, title: item, width: "100px"});

            }
            angular.forEach($scope.columns, function (columnsItem) {
                if (columnsItem.title == "_source") {
                    $scope.columns.splice(1, 1);
                }
            });
        }

        $scope.removeSelected = function (index, item) {
            var i = 0;
            if (index > -1) {
                $scope.selected.splice(index, 1);
            }
            $scope.available.splice(index, 0, item);
            angular.forEach($scope.columns, function (columnsItem) {
                i++;
                if (columnsItem.title == item) {
                    $scope.columns.splice(i - 1, 1);
                } else if ("@" + columnsItem.title == item) {
                    $scope.columns.splice(i - 1, 1);
                }
                if ($scope.columns.length == 1) {
                    $scope.columns.push({
                        field: "_source", title: "_source", width: "600px", template: function (dataItem) {
                            return JSON.stringify(dataItem["_source"]);
                        }
                    });
                }
            })

        }


        //文档高度
        function getDocumentTop() {
      var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                // 上翻后会出现小数，文档高度向上取整
                documentScrollTop = Math.ceil(document.documentElement.scrollTop);
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }

        //可视窗口高度
        function getWindowHeight() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }

        //滚动条滚动高度
        function getScrollHeight() {
            var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }

        window.onscroll = function () {

            if ((getDocumentTop() + getWindowHeight() == getScrollHeight()) && isLoadMore) {
                requestData.from += 30;


                  // console.log($scope.selected);

                // let arr = $scope.selected.map((item,index)=>{
                //
                // if (item == "@timestamp") {
                //     item = 'timestamp';
                // } else if (item == '@version') {
                //     item = 'version';
                // }
                // if (item.indexOf("_") != -1 && item.indexOf("_source") == -1 && $scope.columns.in_array(item) == true) {
                //     $scope.columns.push({field: item, title: item, width: "200px"});
                // }
                // else if ( $scope.columns.in_array(item) == true) {
                //     $scope.columns.push({field: "_source." + item, title: item, width: "100px"});
                //
                // }
                // angular.forEach($scope.columns, function (columnsItem) {
                //     if (columnsItem.title == "_source") {
                //         $scope.columns.splice(1, 1);
                //     }
                // });
                // });

                console.log($scope.available);

                console.log($scope.columns);
                $scope.ELKGridOptions.dataSource.read();

                // console.log($scope.selected);
                // if ($scope.selected.length == 0){
                //     $scope.ELKGridOptions.dataSource.read();
                // }

                  //console.log($scope.selected.length);

            }
        }
        //判断某个元素是否在数组中
        Array.prototype.S=String.fromCharCode(2);
        Array.prototype.in_array=function(e){
            var r=new RegExp(this.S+e+this.S);
            return (r.test(this.S+this.join(this.S)+this.S));
        };



        function xyAxisData(analysisData) {
            var xTime = [];
            var yCount = [];
            angular.forEach(analysisData, function (item) {
                    xTime.push(timestampToTime(item.key));
                    yCount.push(item.doc_count);
                }
            );
            $scope.option = {
                grid: {
                    left: '3%',
                    right: '4%',
                    containLabel: true
                },
                legend: {
                    data: ['Conunt']
                },
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        xAxisIndex: [0],
                        handleSize: 20,
                        dataBackgroundColor: '#eee',
                        fillerColor: 'rgba(144,197,237,0.2)',
                        handleColor: '#1790cf',

                    }


                ],
                tooltip: {
                    trigger: 'item',
                    formatter: function (data) {
                        return 'Count：&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;' + data.data + '<br/>' + '<hr/>' + "@timestamp per 30 minutes ：" + data.name;
                    }
                },


                xAxis: {
                    type: 'category',
                    data: xTime,
                    name: '@timestamp per 30 minutes',
                    nameLocation: "center",
                    nameGap: "25",
                    nameTextStyle: {
                        fontSize: 12
                    },


                },
                yAxis: {
                    type: 'value',

                    nameLocation: "center",
                    nameTextStyle: {
                        fontWeight: "bolder",
                        fontSize: 16,
                        color: "#848E96"
                    },
                    nameRotate: "90",
                    nameGap: 100,


                },
                series: [
                    {
                        name: 'Count',
                        data: yCount,
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                color: '#57C17B'
                            }
                        }
                    }

                ]
            };
        }

        function timestampToTime(timestamp) {
            var date = new Date(timestamp + 8 * 3600 * 1000);
            return date.toJSON().substr(0, 19).replace('T', ' ');
        }

        function generate() {
            array.length = 0;
            if ($scope.param.key == "" || $scope.param.key == null) {
                $scope.param.key = "*";
            }
            var data = {
                "query": {
                    "filtered": {
                        "query": {
                            "query_string": {
                                "query": $scope.param.key,
                                "analyze_wildcard": true
                            }
                        },
                        "filter": {
                            "bool": {
                                "must": [
                                    {
                                        "range": {
                                            "@timestamp": {
                                                "gte": $scope.param.startTime,
                                                "lte": $scope.param.endTime
                                            }
                                        }
                                    }
                                ],
                                "must_not": []
                            }
                        }
                    }
                },
                "sort": {
                    "@timestamp": {
                        "order": "desc"
                    }
                },
                "aggs": {
                    "agg_dateHistogram": {
                        "date_histogram": {
                            "field": "@timestamp",
                            "interval": "30m",
                            "time_zone": "Asia/Shanghai",
                            "min_doc_count": 0,
                            "extended_bounds": {
                                "min": $scope.param.startTime,
                                "max": $scope.param.endTime
                            }
                        }
                    }
                },
                "size": 30,
                "from": 0
            };

            return data;
        }


    }
})();

